import React, { useCallback, useEffect, useRef, useState, useImperativeHandle, forwardRef } from 'react';
import { Checkbox, Tooltip } from 'antd';
import { TableRefProps } from '@library/components/table/interface';
import DropdownColumnsSet from './DropdownColumnsSet';
import {
  Admin,
  cacheKeyFun,
  columnsMapObj,
  delColumnsSetApi,
  getColumnsSetApi,
  handleUserId,
  setColumnsApi
} from './Api';
import { PACKAGE_NAME } from '@library/app/automatic/package';
import { message } from '@library/utils';
import style from './style.module.scss';
import { CURR_PAGE_SIZE, getColumnWidth } from '@library/components/table/util';
import { v4 as uuid } from 'uuid';
interface Props {
  columns: any[];
  businessId: string; // 存储的id eg: manufacture.Amecprojectreport (模块.表名)
  onSendColumns?: (list: any) => void;
  showAutoLoad?: boolean;
  tableRef?: React.RefObject<TableRefProps>;
}

export const useSetColumnsFun = (columnsOrigin: any) => {
  const [columns, setColumns] = useState<any>([]);

  useEffect(() => {
    columnsOrigin?.length &&
      setColumns([
        ...columnsOrigin
          .map((ele: any) => ({ ...ele }))
          .filter((ele: any) => {
            if (ele.isFixedLeft) ele.fixed = 'left';
            else if (ele.isFixedRight) ele.fixed = 'right';
            else delete ele.fixed;
            ele.width = ele.width || 100;
            ele.ellipsis = true;
            return ele.checked;
          })
      ]);
  }, [columnsOrigin]);

  return columns;
};

export const ColumnsSetButton = forwardRef(
  ({ columns, businessId, onSendColumns, showAutoLoad, tableRef }: Props, ref: React.Ref<any>) => {
    const [columnsObj, setColumnsObj] = useState<any>({});
    const [columnsOrigin, setColumnsOrigin] = useState<any>([]);
    const [columnsCopy, setColumnsCopy] = useState<any>([]);
    const [autoLoad, setAutoLoad] = useState(false);
    const initGetColumnsTimer = useRef<any>(null);

    useImperativeHandle(ref, () => ({
      getId: () => {
        return columnsObj.id;
      }
    }));

    const initGetColumns = useCallback(async () => {
      if (columns?.length) {
        let result: any = [];
        const obj = await getColumnsSetApi(businessId!);
        if (obj && Object.keys(obj).length > 0) {
          try {
            result = JSON.parse(obj.setting);

            // 加载数据
            setAutoLoad(obj.autoLoad);
            if (obj.autoLoad) tableRef?.current?.onRefresh?.();
          } catch (error) { }
          // 首次进来 永远用模型上的来覆盖原始的
          const commMap = {},
            originMap = {};
          columns.forEach((ele: any) => (originMap[ele.dataIndex] = { ...ele }));
          result.forEach((ele: any) => {
            // 更新
            if (!ele.uuid) ele.uuid = uuid();
            if (ele.isFixedLeft) ele.fixed = 'left';
            if (ele.isFixedRight) ele.fixed = 'right';
            if (originMap[ele.dataIndex]) {
              delete originMap[ele.dataIndex].checked;
              delete originMap[ele.dataIndex].fixed;
              delete originMap[ele.dataIndex].isFixedLeft;
              delete originMap[ele.dataIndex].isFixedRight;
              delete originMap[ele.dataIndex].width;
              Object.assign(ele, originMap[ele.dataIndex]);
            }
            commMap[ele.dataIndex] = ele;
          });
          columns.forEach((item: any) => {
            // 新增
            if (!commMap[item.dataIndex])
              commMap[item.dataIndex] = {
                ...item,
                checked: item.checked === false ? false : true
              };
          });
          result.forEach((ele: any) => {
            // 删除
            if (!originMap[ele.dataIndex]) delete commMap[ele.dataIndex];
          });
          result = Object.values(commMap);
          const left = result.filter((ele: any) => ele.fixed === 'left');
          const center = result.filter((ele: any) => !ele.fixed);
          const right = result.filter((ele: any) => ele.fixed === 'right');
          result = [...left, ...center, ...right];
          obj.setting = JSON.stringify(result);
          setColumnsObj(obj);
          if (typeof columnsMapObj === 'object') columnsMapObj[cacheKeyFun(businessId)] = { ...obj };
        } else {
          result = columns;
          result.forEach((item: any) => {
            item.id = item.dataIndex;
            item.uuid = uuid();
            item.pageSize = 20;
            item.checked = item.checked === false ? false : true;
            if (item.fixed) {
              item.isFixedLeft = item.fixed === 'left';
              item.isFixedRight = item.fixed === 'right';
            }
          });

          columnsMapObj[cacheKeyFun(businessId)] = { setting: JSON.stringify(result) };
          setColumnsObj({});
        }

        setColumnsOrigin(result);
        setColumnsCopy([...result].map((ele) => ({ ...ele })));
      }
    }, [columns, businessId, tableRef]);

    useEffect(() => {
      const obj = columnsMapObj?.[cacheKeyFun(businessId)];

      if (obj && Object.keys(obj).length > 0) {
        try {
          setColumnsObj(obj);
          const result = JSON.parse(obj.setting);
          setColumnsOrigin(result);
          setColumnsCopy([...result].map((ele) => ({ ...ele })));

          // 加载数据
          setAutoLoad(obj.autoLoad);
          if (obj.autoLoad) tableRef?.current?.onRefresh?.();
        } catch (error) { }
      } else {
        if (initGetColumnsTimer.current) {
          clearTimeout(initGetColumnsTimer.current);
        }

        initGetColumnsTimer.current = setTimeout(() => {
          initGetColumns();
          initGetColumnsTimer.current = null;
        }, 200);
      }
    }, [initGetColumns, businessId, tableRef]);

    useEffect(() => {
      if (columnsOrigin?.length) onSendColumns?.(columnsOrigin);
    }, [columnsOrigin, onSendColumns]);

    const columnsSaveFun = useCallback(async () => {
      let columnsObjCopy = { ...columnsObj };
      if (columnsObjCopy.businessId !== businessId) columnsObjCopy = {};

      const id = handleUserId() !== columnsObjCopy.userId ? undefined : columnsObjCopy.id;

      if (columnsObjCopy.widthFlag) {
        columnsOrigin.forEach((ele: any) => {
          if (ele.uuid) {
            const width = getColumnWidth(ele.uuid);
            if (width) ele.width = Number(width) || 130;
          }
        });
      }
      if (columnsObjCopy.pageSizeFlag) {
        const pageSize = window.sessionStorage.getItem(CURR_PAGE_SIZE);
        columnsObjCopy.pageSize = pageSize;
        columnsOrigin.forEach((ele: any) => {
          ele.pageSize = pageSize;
        });
      }

      const data = {
        ...columnsObjCopy,
        autoLoad,
        id: id,
        module: PACKAGE_NAME,
        businessId: businessId,
        contentType: 'table',
        functionUrl: businessId,
        setting: JSON.stringify(columnsOrigin)
      };
      const res = await setColumnsApi(data);
      setColumnsObj(res);
      columnsMapObj[cacheKeyFun(businessId)] = res;
      setColumnsOrigin([...columnsOrigin]);
      setColumnsCopy([]);
    }, [columnsObj, columnsOrigin, businessId, autoLoad]);

    const columnsRecoverFun = useCallback(async () => {
      if (handleUserId() !== Admin && columnsObj.userId === Admin) return;

      const id = columnsMapObj[cacheKeyFun(businessId)].id;
      await delColumnsSetApi(id, businessId);

      setColumnsObj({});
      setColumnsCopy([]);
      await initGetColumns();
    }, [columnsObj.userId, businessId, initGetColumns]);

    const columnsShareFun = useCallback(async () => {
      const id = columnsMapObj[cacheKeyFun(businessId)].id;
      if (!id) return message.error(window.$app.t('saveFirst'));

      const data = {
        id,
        businessId,
        shareFlag: true
      };
      const res = await setColumnsApi(data);
      setColumnsObj(res);
    }, [businessId]);

    const onChangeCheckBox = useCallback(
      (key: string) => (e: any) => {
        const checked = e.target.checked;
        setColumnsObj((prev: any) => {
          return { ...prev, [key]: checked };
        });
      },
      []
    );

    return (
      <Tooltip title={window.$app.t('setting')}>
        <DropdownColumnsSet
          columns={columnsOrigin}
          setColumns={setColumnsOrigin}
          columnsCopy={columnsCopy}
          columnsSaveFun={columnsSaveFun}
          columnsRecoverFun={columnsRecoverFun}
          columnsShareFun={columnsShareFun}
        >
          <div className={style.defaultFlagStyle}>
            {showAutoLoad && (
              <div className={style.flagStyle}>
                <Checkbox onChange={(e) => setAutoLoad?.(e.target.checked)} checked={autoLoad}>
                  {window.$app.t('autoLoad')}
                </Checkbox>
              </div>
            )}
            <div className={style.flagStyle}>
              <Checkbox onChange={onChangeCheckBox('widthFlag')} checked={columnsObj.widthFlag}>
                {window.$app.t('saveCurrWidth')}
              </Checkbox>
            </div>
            <div className={style.flagStyle}>
              <Checkbox onChange={onChangeCheckBox('pageSizeFlag')} checked={columnsObj.pageSizeFlag}>
                {window.$app.t('saveCurrPageSize')}
              </Checkbox>
            </div>
          </div>
        </DropdownColumnsSet>
      </Tooltip>
    );
  }
);
